"use client";

import { useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { Card } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import clsx from "clsx";

interface StatRow {
  major: string;
  student_count: number;
}

export interface StudentStat {
  student_id: string;
  name: string;
  student_tag: string;
  major: string;

  course_count: number;
  total_credit: number;
  total_credit_gpa: number;
  avg_gpa: number;

  gpa_rank: number;
  ranked_score: number;
  major_top_gpa: number;
}

export default function UploadExcelPage() {
  const [stats, setStats] = useState<StatRow[]>([]);
  const [fileName, setFileName] = useState("");
  const [loading, setLoading] = useState(false);
  const [selectedMajor, setSelectedMajor] = useState<string | null>(null);
  const [studentStats, setStudentStats] = useState<StudentStat[]>([]);

  // ✅ 查询专业总览
  const fetchStats = async () => {
    const res = await fetch("/api/gpa/major-stat");
    const data = await res.json();
    setStats(data);
  };

  // ✅ 查询某个专业的学生统计
  const fetchStudentStats = async (major: string) => {
    setSelectedMajor(major);
    const res = await fetch(
      `/api/gpa/by-major?major=${encodeURIComponent(major)}`
    );
    const data = await res.json();
    setStudentStats(data);
  };

  const open_detail = (sid: string) => {
    window.open(`/gpa/detail/${sid}`, "_blank");
  };

  useEffect(() => {
    fetchStats();
  }, []);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setFileName(file.name);
    setLoading(true);

    const formData = new FormData();
    formData.append("file", file);

    const res = await fetch("/api/gpa/excel", {
      method: "POST",
      body: formData,
    });

    const result = await res.json();
    if (result.status === "success") {
      await fetchStats();
    }

    setLoading(false);
  };

  return (
    <div className="p-6 space-y-2 flex flex-col">
      {/* 中间类似标题的内容 */}
      <div className="text-center gap-2">
        <h1 className="text-2xl font-semibold">信息管理学院保研测算表</h1>
        <p className="text-sm">
          如果没有显示数据，选择初始成绩进行上传；如果需要更新则上传新的excel成绩表
          。
        </p>
      </div>
      <div className="flex p-2 flex-row gap-6 justify-center">
        {/* 左边的内容 */}
        <div
          className={clsx(
            "flex flex-col gap-4 transition-all duration-300",
            selectedMajor ? "max-w-[400px]" : "max-w-full"
          )}
        >
          <Card className="p-4 space-y-4 border-gray-200 shadow-md rounded-md">
            <Input
              type="file"
              accept=".xlsx,.xls"
              onChange={handleUpload}
              placeholder="选择上传成绩Excel"
            />
            {fileName && (
              <p className="text-sm text-gray-500">已选择文件：{fileName}</p>
            )}
            {loading && (
              <p className="text-blue-600 text-sm">正在上传与刷新...</p>
            )}
          </Card>

          {stats.length > 0 && (
            <Card className="p-4 overflow-auto  border-gray-200 shadow-md rounded-md">
              <h2 className="text-lg font-medium mb-4">专业人数统计</h2>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>专业名称</TableHead>
                    <TableHead>学生人数</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stats.map((row, index) => (
                    <TableRow
                      key={index}
                      className="cursor-pointer hover:bg-muted"
                      onClick={() => fetchStudentStats(row.major)}
                    >
                      <TableCell>{row.major}</TableCell>
                      <TableCell>{row.student_count}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Card>
          )}
        </div>
        {/* 右边点击成绩的内容 */}
        {selectedMajor && (
          <Card className="p-4 overflow-auto flex-1 border-gray-200 shadow-md rounded-md min-w-[600px] max-w-[75w] gap-2">
            <p className="text-md font-semibold w-full text-center">
              {selectedMajor}成绩测算表
            </p>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>排名</TableHead>
                  <TableHead>学号</TableHead>
                  <TableHead>姓名</TableHead>
                  <TableHead>专业</TableHead>
                  <TableHead>课程数量</TableHead>
                  <TableHead>总学分数</TableHead>
                  <TableHead>总绩点数</TableHead>
                  <TableHead>平均GPA</TableHead>
                  <TableHead>核算得分</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {studentStats.map((s, idx) => (
                  <TableRow
                    key={idx}
                    className="cursor-pointer hover:bg-muted"
                    onClick={() => open_detail(s.student_id)}
                  >
                    <TableCell>{s.gpa_rank}</TableCell>
                    <TableCell>{s.student_id}</TableCell>
                    <TableCell>{s.name}</TableCell>
                    <TableCell>{s.major}</TableCell>
                    <TableCell>{s.course_count}</TableCell>
                    <TableCell>{s.total_credit}</TableCell>
                    <TableCell>{s.total_credit_gpa}</TableCell>
                    <TableCell>{s.avg_gpa}</TableCell>
                    <TableCell>{s.ranked_score}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Card>
        )}
      </div>
    </div>
  );
}
